import { LoadingOutlined, TagsOutlined } from "@ant-design/icons";
import { ThoughtChain, XRequest } from "@ant-design/x";
import { Button, Descriptions, Space } from "antd";
import React,{useState} from "react";
import axios from "axios";
import { XStream } from '@ant-design/x';
import type { ThoughtChainItem } from "@ant-design/x";
import { parsePack } from './parse'
import token from '@/api/token'

/**
 * 🔔 Please replace the BASE_URL, PATH, MODEL, API_KEY with your own values.
 */
const BASE_URL = "http://172.16.1.118:7861";
const PATH = "/chat/chat";
const MODEL = "Qwen1.5-14B-Chat";
// const API_KEY = '';
// console.log(XRequest,"XRequest")
async function mockFetch() {
  const response = await axios.post(BASE_URL + PATH, {
    // 使用传递的 headers

    responseType: "stream",

    // messages: [{ role: 'user', content: 'hello, who are u?' }],
    stream: true,
    conversation_id: "0897e181998c4bff8c96e64055092ac7",
    history_len: 0,
    max_tokens: 0,
    model_name: "Qwen1.5-14B-Chat",
    prompt_name: "default",
    query: "nihao",
    temperature: 0.7,
    user_id: 356,

    // 如果是流式响应，设置为 stream
  });
  // 将 axios 响应转换为符合 `fetch` API 的 Response 对象
  const reader = response.data.getReader();
  const stream = new ReadableStream({
    start(controller) {
      reader.read().then(function processText({ done, value }) {
        if (done) {
          controller.close();
          return;
        }
        controller.enqueue(value);
        reader.read().then(processText);
      });
    },
  });
  return new Response(stream, {
    headers: {
      Authorization: `Bearer ${localStorage.getItem("react_token")}`,
    },
  });
}
const exampleRequest = XRequest({
  baseURL: BASE_URL + PATH,
  fetch:async () => {
    const response = await fetch(BASE_URL + PATH, {
      method: "POST",
      body: JSON.stringify({
        // messages: [{ role: 'user', content: 'hello, who are u?' }],
        stream: true,
        conversation_id: "0897e181998c4bff8c96e64055092ac7",
        history_len: 0,
        max_tokens: 0,
        model_name: "Qwen1.5-14B-Chat",
        prompt_name: "default",
        query: "nihao",
        temperature: 0.7,
        user_id: 356,
      }),
      headers: {
        Authorization: `Bearer ${localStorage.getItem("react_token")}`,
        "Content-Type": "application/json",
      },
    });
    // console.log(typeof(response.body),"response")
    // for await (const chunk of XStream({
    //   readableStream: response.body,
    // })) {
    //   // 你的协议
    //   console.log(chunk);
    // }
   return response
  },

});

const App = (nextContent: string) => {
  const [status, setStatus] = React.useState<ThoughtChainItem["status"]>();
  const [lines, setLines] = React.useState<Record<string, string>[]>([]);
  const [msgall, setMsgall] = useState("")

  async function request() {
    setStatus("pending");

    await exampleRequest.create(
      {
        // messages: [{ role: 'user', content: 'hello, who are u?' }],
        // stream: true,
        // conversation_id: "0897e181998c4bff8c96e64055092ac7",
        // history_len: 0,
        // max_tokens: 0,
        // model_name: "Qwen1.5-14B-Chat",
        // prompt_name: "default",
        // query: "nihao",
        // temperature: 0.7,
        // user_id: 356,
      },
      {
        onSuccess: async (messages) => {
          setStatus("success");
          // console.log("onSuccess", msg);
          // for await (const chunk of XStream({
          //   readableStream: messages,
          // })) {
          //   console.log(chunk);
          //   setLines((pre) => [...pre, chunk]);
          // }

        },
        onError: (error) => {
          setStatus("error");
          console.error("onError", error);
        },
        onUpdate:async(msg) => {
          
          setLines((pre) => [...pre, msg]);
          const chunk: any[] = parsePack(msg)
          const data = { text: '', conversationId: '', messageId: '', kbId: 0, docs:[] }
          chunk.forEach((msg) => {
           
              data.text += msg.answer || ''
              data.conversationId = msg.conversation_id
              data.messageId = msg.message_id
              data.kbId = msg.kb_id
            
          })
          setMsgall((prevText) => prevText + data.text);
          console.log("onUpdate", msgall);
          //  for await (const chunk of XStream({
          //   readableStream: msg.data,
          // })) {
          //   console.log(chunk);
          //   // setLines((pre) => [...pre, chunk]);
          // }
        },
      },
      new TransformStream<string, string>({
        
      async  transform(chunk, controller) {
          // console.log(chunk,"chunk")
          // console.log(controller,"controller")
          controller.enqueue(chunk);
          // for await (const chunk of XStream({
          //   readableStream: response,
          // })) {
          //   // 你的协议
          //   console.log(chunk);
          // }
        },
      }),
    );
  }

  return (
   <>
   <div>{msgall}</div>
    <Space align="start" size={16}>
      <Button type="primary" disabled={status === "pending"} onClick={request}>
        Request - {BASE_URL}
        {PATH}
      </Button>
      
      <ThoughtChain
        items={[
          {
            title: "Request Log",
            status: status,
            icon: status === "pending" ? <LoadingOutlined /> : <TagsOutlined />,
            description:
              status === "error" &&
              exampleRequest.baseURL === BASE_URL + PATH &&
              "Please replace the BASE_URL, PATH, MODEL, API_KEY with your own values.",
            content: (
              
              <Descriptions column={1}>
                <Descriptions.Item label="Status">
                  {status || "-"}
                </Descriptions.Item>
                <Descriptions.Item label="Update Times">
                  {lines.length}
                  
                </Descriptions.Item>
              </Descriptions>
            ),
          },
        ]}
      />
    </Space>
    </>
  );
};

export default App;
